﻿using System.Web.Mvc;
using Kaiser.Models;
using Kaiser.Extensions;
namespace Kaiser.ModelBinders
{
    public class PagingInfoModelBinder : IModelBinder
    {
        private const string PageSizeRouteDataName = "rows";
        private const string PageNumberRouteDataName = "page";

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProvider = bindingContext.ValueProvider;

            int size = 10;
            int index = 0;

            string pageSize = null, pageNumber=null;
         
            if (valueProvider.GetValue(PageSizeRouteDataName)!=null)
            {
              pageSize = valueProvider.GetValue(PageSizeRouteDataName).AttemptedValue;
            }
            if (valueProvider.GetValue(PageNumberRouteDataName)!=null)
            {
                pageNumber = valueProvider.GetValue(PageNumberRouteDataName).AttemptedValue;
            }
         

            if (!pageSize.IsNullOrWhiteSpace())
            {
                int.TryParse(pageSize, out size);
                //如果非法输入每页显示数，重置为10
                if (size < 1)
                    size = 10;
            }

            if (!pageNumber.IsNullOrWhiteSpace() && int.TryParse(pageNumber, out index))
            {
                index--;
                //如果非法输入页数，重置为0
                if (index < 0)
                    index = 0;
            }

            var pageinfo = new PagingInfo(index, size);

             if (valueProvider.GetValue("order")!=null)
            {
                pageinfo.Order = valueProvider.GetValue("order").AttemptedValue;
            }
             if (valueProvider.GetValue("sort") != null)
             {
                 pageinfo.Sort = valueProvider.GetValue("sort").AttemptedValue;
             }

             return pageinfo;
        }
    }
}